<template>
  <Dialog :appDialog="appDialog">
    <div class="addRules-box">
      <div class="title">
        规则设置：
        <el-button class="addBtn" @click="addRuleFun">添加子规则</el-button>
      </div>
      <el-scrollbar height="500px">
      <div class="rule-content">
        <div v-if="ruleArr.length">
          <div class="item" v-for="(item, index) in ruleArr" :key="item">
            <div class="stepBox" v-if="index <= ruleArr.length - 2">
              <div class="word">且</div>
              <div class="line"></div>
            </div>
            <span>规则{{ index + 1 }}:</span>
            <el-cascader style="width: 280px" :props="{ label: 'name', value: 'id' }" v-model="item.cust_rule_type_ids" :options="typeArr" @change="handleChange(item)" />
            <span v-if="item.cust_rule_type_ids.length && item.classify != 2">{{ item.classify == 1 ? '为' : item.classify == 4 ? '满足' : item.classify == 3 ? '的阶段为' : '' }}</span>

            <el-select v-if="item.cust_rule_type_ids.length && item.classify == 1 && item.cust_rule_type != 7" v-model="item.action_type" placeholder="请选择" style="width: 180px">
              <el-option v-for="item in operationArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-select v-if="item.cust_rule_type_ids.length && item.cust_rule_type == 7" v-model="item.action_type" placeholder="请选择" style="width: 180px">
              <el-option v-for="item in bindCustArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-select v-if="item.cust_rule_type_ids.length && (item.classify == 2 || item.classify == 5 || item.classify == 6)" v-model="item.operator_type" placeholder="请选择" style="width: 180px; margin: 0 10px">
              <el-option v-for="item in numRuleArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-input-number :precision="0" v-if="item.cust_rule_type_ids.length && (item.classify == 2 || item.classify == 5)" style="width: 140px" v-model="item.num" :min="0" />
            <el-input-number v-if="item.cust_rule_type_ids.length && item.classify == 6" v-model="item.num" :precision="2" style="width: 140px" :step="0.1" :min="0" />
            <span>{{ item.classify == 2 ? '个' : item.classify == 5 ? '秒' : item.classify == 6 ? '元' : '' }}</span>
            <el-select multiple v-if="item.cust_rule_type_ids.length && item.classify == 3" v-model="item.cust_stageIdList" @change="changeCustStage(item)" placeholder="请选择客户阶段" style="width: 180px; margin: 0 10px">
              <el-option v-for="item in props.tableList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <div v-if="item.cust_rule_type_ids.length && item.cust_rule_type == 6">
              <el-select multiple v-model="item.cust_sourceList" @change="changeCustSource(item)" placeholder="请选择客户来源" style="width: 180px; margin: 0 10px">
                <el-option v-for="item in sourceList" :key="item.id" :label="item.name" :value="item.id" /> </el-select
              >中任意一个
            </div>

            <div class="tag" v-if="item.cust_rule_type_ids.length && item.classify == 4 && item.cust_rule_type != 6">
              <el-select popper-class="zw-hide_select_option" @click="openBatchLabel(item)" @change="changeCustTag(item)" style="width: 220px" v-model="item.cast_tagIdList" multiple placeholder="选择客户标签">
                <el-option v-for="v in item.cast_tag" :key="v.id" :label="v.name" :value="v.id">{{ v.name }}</el-option>
              </el-select>
              <!-- <div class="desc" @click="openBatchLabel(item)">选择标签</div> -->
              <span>{{ !item.cust_tag_type ? '无标签' : item.cust_tag_type == 3 ? '无标签' : `中${item.cust_tag_type == 1 ? '同时满足所有标签' : '任意一个标签'}` }}</span>
            </div>
            <img class="imgdel" @click="dellist(index)" src="@/assets/customer/del-icon.png" alt="" />
          </div>
        </div>
        <el-empty v-else image="/static/noData.png" description="暂无数据"></el-empty>
      </div>
      </el-scrollbar>
    </div>
    <BatchLabel ref="BatchLabelRef" @save="getLabelFun" />
  </Dialog>
</template>

<script setup lang="ts">
  import BatchLabel from '@/components/BatchLabel.vue'
  import Dialog from '@/components/Dialog.vue'
  import { ref, watch } from 'vue'
  import { ruleGroupEdit, ruleGroupCreate, ruleGroupTree } from '../../api'
  import { ElMessage } from 'element-plus'
  const props = defineProps(['tableList', 'stage_id'])
  import { IsNotEmpty } from '@/utils/utils'
  import { customerSource } from '@/api/rules'
  const ruleArr: any = ref([])
  const tableList = ref([])
  const sourceList = ref([])
  const emit = defineEmits(['save'])
  const dellist = (index: any) => {
    ruleArr.value.splice(index, 1)
  }
  //获取客户来源
  const getCustomer = () => {
    customerSource({ page: 1, page_size: 9999 }).then((res: any) => {
      sourceList.value = []
      if (res.data) {
        res.data.forEach((item: any) => {
          sourceList.value.push(item)
        })
      }
    })
  }
  getCustomer()
  // 选择类型
  const handleChange = (val: any) => {
    console.log(props.tableList, 'props.tableList')
    let index = typeArr.value.findIndex((it: any) => {
      return it.id == val.cust_rule_type_ids[0]
    })
    if (index > -1) {
      if (val.cust_rule_type_ids.length == 1) {
        val.classify = typeArr.value[index].classify
        val.cust_rule_type = typeArr.value[index].type
        val.cust_rule_id = typeArr.value[index].id
        val.desc = typeArr.value[index].name
        return
      }
      let indx = typeArr.value[index].children.findIndex((it: any) => {
        return it.id == val.cust_rule_type_ids[1]
      })

      if (indx > -1) {
        if (val.cust_rule_type_ids.length == 2) {
          val.classify = typeArr.value[index].children[indx].classify
          val.cust_rule_type = typeArr.value[index].children[indx].type
          val.cust_rule_id = typeArr.value[index].children[indx].id
          val.desc = typeArr.value[index].name + '>' + typeArr.value[index].children[indx].name
          console.log(val.desc, 5555)
          return
        }
        let ind = typeArr.value[index].children[indx].children.findIndex((it: any) => {
          return it.id == val.cust_rule_type_ids[2]
        })
        if (ind > -1) {
          if (val.cust_rule_type_ids.length == 3) {
            val.classify = typeArr.value[index].children[indx].children[ind].classify
            val.cust_rule_type = typeArr.value[index].children[indx].children[ind].type
            val.cust_rule_id = typeArr.value[index].children[indx].children[ind].id
            val.desc = typeArr.value[index].name + '>' + typeArr.value[index].children[indx].name + '>' + typeArr.value[index].children[indx].children[ind].name
            return
          } else {
            let lst = typeArr.value[index].children[indx].children[ind].children.findIndex((it: any) => {
              return it.id == val.cust_rule_type_ids[3]
            })
            val.classify = typeArr.value[index].children[indx].children[ind].children[lst].classify
            val.cust_rule_type = typeArr.value[index].children[indx].children[ind].children[lst].type
            val.cust_rule_id = typeArr.value[index].children[indx].children[ind].children[lst].id
            val.desc = typeArr.value[index].name + '>' + typeArr.value[index].children[indx].name + '>' + typeArr.value[index].children[indx].children[ind].name + '>' + typeArr.value[index].children[indx].children[ind].children[lst].name
            return
          }
        }
      }
    }
  }
  const BatchLabelRef = ref(null)
  //  type 1 下拉框   2 数字   3标签  4客户阶段
  const typeArr = ref([])

  // 新增规则
  const addRuleFun = () => {
    ruleArr.value.push({
      cast_tagIdList: [],
      cust_stageIdList: [],
      cust_sourceList: [],
      cust_rule_id: '',
      cust_rule_type: '',
      action_type: '',
      desc: '',
      operator_type: '',
      num: 0,
      cust_stage: [],
      cust_tag_type: '',
      cast_tag: [],
      cust_rule_type_ids: [],
      cust_source: []
    })
  }
  const operationArr = ref([
    { label: '添加员工', value: 1 },
    { label: '删除员工', value: 2 }
  ])
  const bindCustArr = ref([
    { label: '未绑定', value: 1 },
    { label: '已绑定', value: 2 }
  ])
  const numRuleArr = ref([
    { label: '大于', value: 1 },
    { label: '等于', value: 2 },
    { label: '大于等于', value: 3 },
    { label: '小于', value: 4 },
    { label: '小于等于', value: 5 }
  ])

  // 更改的客户阶段
  const changeCustStage = (val: any) => {
    val.cust_stage = []
    val.cust_stageIdList.forEach((item: any) => {
      let index = tableList.value.findIndex((it: any) => {
        return it.id == item
      })
      if (index > -1) {
        val.cust_stage.push({
          id: tableList.value[index].id,
          name: tableList.value[index].name
        })
      }
    })
  }
  //更改客户来源
  const changeCustSource = (val: any) => {
    val.cust_source = []
    val.cust_sourceList.forEach((item: any) => {
      let index = sourceList.value.findIndex((it: any) => {
        return it.id == item
      })
      if (index > -1) {
        val.cust_source.push({
          id: sourceList.value[index].id,
          name: sourceList.value[index].name
        })
      }
    })
  }
  // 更改标签
  const changeCustTag = (val: any) => {
    console.log(val, '======删除标签前---')
    val.cast_tag = val.cast_tag.filter((item: any) => val.cast_tagIdList.includes(item.id))
    console.log(val, '++++删除标签 ---', val.cust_stageIdList)
  }

  let openBatchLabelData = {} //当前选择的是那个数据
  // 打开选择标签弹框
  const openBatchLabel = (val: any) => {
    console.log(val, '打开弹框')
    openBatchLabelData = val
    BatchLabelRef.value.dialogVisible = true
    BatchLabelRef.value.dialogData.labelChooseType = 2
    BatchLabelRef.value.chooseDataArr = val.cast_tag
  }
  const getTagType = (num: number) => {
    switch (num) {
      case 0:
        return 3
      case 1:
        return 2
      case 2:
        return 1
    }
  }
  // 获取标签
  const getLabelFun = (val: any) => {
    console.log(val, '===选择')
    openBatchLabelData.cust_tag_type = getTagType(val.labelType)
    // 无标签
    if (val.labelType == 0) {
      openBatchLabelData.cast_tag = []
      openBatchLabelData.cast_tagIdList = []
      openBatchLabelData.cast_tag = []
      return
    }
    openBatchLabelData.cast_tag = val.data
    openBatchLabelData.cast_tagIdList = val.idList
    openBatchLabelData.cast_tag = val.data.map((it: any) => {
      return {
        id: it.id,
        name: it.name
      }
    })
  }
  const getRuleTree = () => {
    ruleGroupTree({}).then((r: any) => {
      typeArr.value = r || []
    })
  }

  const cancelHandel = () => {
    appDialog.value.visible = false
  }
  const submitHandel = () => {
    let canSubmit = true
    let errorIndex = -1
    if (!ruleArr.value.length) {
      ElMessage.error('请添加子规则')
      return
    }
    ruleArr.value.forEach((val: any, index: number) => {
      if (!val.cust_rule_type_ids.length) {
        canSubmit = false
      }
      if (!val.action_type && val.classify == 1) {
        canSubmit = false
      }
      if (!val.operator_type && (val.classify == 2 || val.classify == 5 || val.classify == 6)) {
        canSubmit = false
      }
      if (!val.cust_stage.length && val.classify == 3) {
        canSubmit = false
      }
      if (!val.cast_tag.length && val.cust_tag_type != 3 && val.classify == 4 && val.cust_rule_type != 6) {
        canSubmit = false
      }
      if (!val.cust_source.length && val.cust_rule_type == 6) {
        canSubmit = false
      }
      if (!canSubmit && errorIndex == -1) {
        errorIndex = index
      }
      if (val.classify == 6) {
        val.num = val.num * 100
      }
    })
    if (!canSubmit) {
      ElMessage.error(`请补充完整第${errorIndex + 1}条规则`)
      return
    }
    if (appDialog.value.editInfo.step) {
      ruleGroupEdit({ stage_id: props.stage_id, rule_list: ruleArr.value, step_rule: appDialog.value.editInfo.step }).then((r: any) => {
        ElMessage.success('编辑成功')
        emit('save')
        appDialog.value.visible = false
      })
      return
    }
    ruleGroupCreate({ stage_id: props.stage_id, rule_list: ruleArr.value }).then((r: any) => {
      ElMessage.success('添加成功')
      emit('save')
      appDialog.value.visible = false
    })
  }
  const appDialog = ref({
    visible: false,
    title: '添加规则',
    width: '994px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确认',
    closeModal: true,
    editInfo: {}
  })

  watch(
    () => appDialog.value.visible,
    (val: boolean) => {
      if (val) {
        ruleArr.value = []
        tableList.value = JSON.parse(JSON.stringify(props.tableList)) //隔离数据 相互影响
        if (appDialog.value.editInfo.step) {
          let arr = JSON.parse(JSON.stringify(appDialog.value.editInfo.list))
          arr.forEach((item: any) => {
            item = Object.assign(
              {
                cust_sourceList: [],
                cast_tagIdList: [],
                cust_stageIdList: [],
                cust_rule_id: '',
                cust_rule_type: '',
                action_type: '',
                desc: '',
                operator_type: '',
                num: 0,
                cust_stage: [],
                cust_tag_type: '',
                cast_tag: [],
                cust_rule_type_ids: [],
                cust_source: []
              },
              item
            )
            item.cast_tagIdList = item.cast_tag.map((it: any) => {
              return it.id
            })
            item.cust_stageIdList = item.cust_stage.map((it: any) => {
              return it.id
            })
            item.cust_sourceList = item.cust_source.map((it: any) => {
              return it.id
            })
            if (item.classify == 6) {
              item.num = item.num / 100
            }
            ruleArr.value.push(item)
          })
        }
        console.log(ruleArr.value, 5666)
        getRuleTree()
      }
    }
  )

  defineExpose({ appDialog })
</script>

<style lang="scss" scoped>
  :deep .el-select__popper.el-popper[role='tooltip'] {
    display: none;
  }
  .addRules-box {
    .title {
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      font-weight: 300;
      color: #33302d;
      margin-bottom: 16px;
      padding-top: 12px;
    }
    .rule-content {
      // height: 500px;
      // overflow-y: auto;
      .item {
        position: relative;
        padding-left: 14px;
        padding-bottom: 33px;
        display: flex;
        align-items: center;
        .imgdel {
          width: 18px;
          height: 18px;
        }
        & > span {
          font-size: 14px;
          font-family: STHeitiSC-Light, STHeitiSC;
          font-weight: 300;
          color: #33302d;
          margin: 10px;
        }
        .stepBox {
          position: absolute;
          font-size: 14px;
          font-family: STHeitiSC-Medium, STHeitiSC;
          font-weight: 500;
          color: #ff6b00;
          left: 0;
          top: 12px;
          display: flex;
          height: calc(100% + 12px);
          align-items: center;
          .word {
            padding: 4px 0;
            background: white;
            position: relative;
            z-index: 2;
          }
          &::after,
          &::before {
            box-sizing: border-box;
            position: absolute;
            content: '';
            left: 2px;
            width: 8px;
            height: 8px;
            background: #ffffff;
            border: 2px solid #ff6b00;
            border-radius: 50%;
          }
          &::before {
            top: 4px;
          }
          &::after {
            bottom: 0;
          }
          .line {
            position: absolute;
            width: 1px;
            border-left: dashed 1px #ffc69e;
            height: calc(100% - 32px);
            left: 6px;
            top: 18px;
            z-index: 1;
          }
        }
        .tag {
          display: inline-block;
          vertical-align: middle;
          margin-left: 20px;
          div {
            display: inline-block;
            vertical-align: middle;
            width: 80px;
            text-align: center;
            height: 40px;
            line-height: 40px;
            cursor: pointer;
          }
          span {
            margin-left: 12px;
          }
        }
      }
    }
    .addBtn {
      height: 36px;
      padding: 0 22px;
      background: #F9F9F9;
      border: 1px solid #EAEAEA;
      line-height: 36px;
      text-align: center;
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      font-weight: 300;
      color: #33302D;
      cursor: pointer;
    }
  }
</style>
